package com.sample.springbatch.common;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;


/**
 * JSON数据统一返回格式
 * @author zwg
 *
 * @param <E>
 */
public class RespResult<E> implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2914677101817844403L;
	//返回码
	private int code;
	//说明内容
	private String message;
	//开始时间
	private Long stime;
	//结束时间
	private Long etime;
	//返回的具体数据
	private E data;
	
	
	public RespResult() {
		super();
		this.stime = System.currentTimeMillis();
	}
	
	
	public RespResult<E> getSuccess(String message, E e){
		setCode(ErrorCode.SUCCESS.getCode());
		setMessage(message);
		setEtime(System.currentTimeMillis());
		data = e;
		return this;
	}
	
	
	public RespResult<E> getSuccess(E e){
		setCode(ErrorCode.SUCCESS.getCode());
		setMessage("成功");
		setEtime(System.currentTimeMillis());
		data = e;
		return this;
	}
	
	public RespResult<E> getFail(int code, String message){
		setCode(code);
		setMessage(message);
		setEtime(System.currentTimeMillis());
		return this;
	}
	
	public RespResult<E> getFail(int code, Exception e){
		setCode(code);
		setMessage(e.getMessage());
		setEtime(System.currentTimeMillis());
		return this;
	}
	

	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public Long getStime() {
		return stime;
	}
	public void setStime(Long stime) {
		this.stime = stime;
	}
	public Long getEtime() {
		return etime;
	}
	public void setEtime(Long etime) {
		this.etime = etime;
	}
	public E getData() {
		return data;
	}
	public void setData(E data) {
		this.data = data;
	}


	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("{\"code\"=\"");
		builder.append(code);
		builder.append("\", \"message\"=\"");
		builder.append(message);
		builder.append("\", \"stime\"=\"");
		builder.append(stime);
		builder.append("\", \"etime\"=\"");
		builder.append(etime);
		
		if(data instanceof Collection){
			builder.append("\", \"data\":").append(((Collection) data).size()).append("}");
		}else if(data instanceof Map){
			builder.append("\", \"data\":").append(((Map) data).size()).append("}");
		}else if(data instanceof String){
			builder.append("\", \"data\":\"").append(data).append("\"}");
		}else{
			builder.append("\", \"data\":").append(data).append("}");
		}
		
		return builder.toString();
	}
	
	
	
	

}
